package com.wxdc.nmgyt.nmgytwydc.activity;

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.BottomNavigationView.OnNavigationItemSelectedListener;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.widget.Toast;

import com.wxdc.nmgyt.nmgytwydc.IMapFunInterface.IMapFunInterface;
import com.wxdc.nmgyt.nmgytwydc.R;
import com.wxdc.nmgyt.nmgytwydc.adapter.FragmentPageAdapter;
import com.wxdc.nmgyt.nmgytwydc.app.MyApp;
import com.wxdc.nmgyt.nmgytwydc.common.BottomNavigationViewHelper;
import com.wxdc.nmgyt.nmgytwydc.common.DoubleClickExit;
import com.wxdc.nmgyt.nmgytwydc.common.PublicField;
import com.wxdc.nmgyt.nmgytwydc.customEnum.TabFragment;
import com.wxdc.nmgyt.nmgytwydc.greendao.ope.CodeBeanDaoOpe;
import com.wxdc.nmgyt.nmgytwydc.model.CodeBean;
import com.wxdc.nmgyt.nmgytwydc.model.backresult.UserRolResultBean;
import com.wxdc.nmgyt.nmgytwydc.presenter.MainPersenter;
import com.wxdc.nmgyt.nmgytwydc.presenter.contract.MainContract;
import com.wxdc.nmgyt.nmgytwydc.utils.LocationServiceUtil;
import com.wxdc.nmgyt.nmgytwydc.utils.Network;
import com.wxdc.nmgyt.nmgytwydc.utils.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;


public class MainActivity extends BaseActivity<MainPersenter> implements OnNavigationItemSelectedListener, OnPageChangeListener, IMapFunInterface,MainContract.View {

    @BindView(R.id.bottom_navigation)
    BottomNavigationView mBottomNavigation;
    @BindView(R.id.viewpager)
    ViewPager mViewpager;
    MenuItem prevMenuItem;
    private final String TAG = this.getClass().getSimpleName();
    FragmentPageAdapter adapter;
    private LocationManager mLocationManager;
    private Location mLocation;
    private LocationListener mLocationListener;
    private MyApp mApp;

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initInject() {
        getActivityComponent().Inject(this);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mApp = MyApp.getInstance();
        mBottomNavigation.setOnNavigationItemSelectedListener(this);
        mBottomNavigation.setSelectedItemId(R.id.navigation_index1);
        BottomNavigationViewHelper.disableShiftMode(mBottomNavigation);
        mViewpager.addOnPageChangeListener(this);
        setViewpager();
        mLocationManager = ((MyApp) getApplication()).mLocationManager;
        mLocationListener = LocationServiceUtil.getInstance(mContext).mLocationListener;
        if (CodeBeanDaoOpe.queryAll(mContext).size() == 0) {//初始化数据
            if (!Network.isConnected(mContext)) {
                mApp.showToastLongMessage(mContext, "首次使用需用户登录进行数据加载");
                return;
            } else {
                mCircleProgressDialog.setText("初始化数据");
                mCircleProgressDialog.showDialog();
                mPersenter.RequestCode();
            }
        }
        mPersenter.RequestUserRol(SharedPreferenceUtil.getSid());
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /*
        底部菜单事件
         */
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        Log.i(TAG, "onNavigationItemSelected: -------------");
        switch (item.getItemId()) {
            case R.id.navigation_index1:
                //showMessage("首页");
                mViewpager.setCurrentItem(0);
                break;
            case R.id.navigation_index2:
                //showMessage("map");
                mViewpager.setCurrentItem(1);
                break;
            case R.id.navigation_index3:
                //showMessage("采集");
                mViewpager.setCurrentItem(2);
                break;
            case R.id.navigation_index4:
                //showMessage("我");
                mViewpager.setCurrentItem(3);
                break;
            default:
                break;
        }
        return false;
    }

    /*
    * 实现OnPageChangeListener接口方法
    * */
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        Log.i(TAG, "onPageSelected: ------------>" + position);
        if (prevMenuItem != null) {
            prevMenuItem.setChecked(false);
        } else {
            mBottomNavigation.getMenu().getItem(0).setChecked(false);
        }
        mBottomNavigation.getMenu().getItem(position).setChecked(true);
        prevMenuItem = mBottomNavigation.getMenu().getItem(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /*
    * 设置ViewPager*/
    private void setViewpager() {
        adapter = new FragmentPageAdapter(getSupportFragmentManager(), new ArrayList<Fragment>());
        adapter.addFragment(TabFragment.from(R.id.navigation_index1).fragment());
        adapter.addFragment(TabFragment.from(R.id.navigation_index2).fragment());
        adapter.addFragment(TabFragment.from(R.id.navigation_index3).fragment());
        adapter.addFragment(TabFragment.from(R.id.navigation_index4).fragment());
        mViewpager.setAdapter(adapter);

    }

    /*地图切换*/

    @Override
    public void switchMap(String firstMapFragmentShow) {
        TabFragment.onDestroy();
        if (firstMapFragmentShow.equals("baiduMap")) {
            adapter.replaceFragment(1, TabFragment.from(R.id.navigation_index2).fragment());
        } else if (firstMapFragmentShow.equals("onlineArcgisMap")) {
            adapter.replaceFragment(1, TabFragment.from(PublicField.onlineArcgisMapNum).fragment());
        } else if (firstMapFragmentShow.equals("localArcgisMap")) {
            adapter.replaceFragment(1, TabFragment.from(PublicField.localArcgisMapNum).fragment());
        }
        Log.i(TAG, "switchMap: --------size:" + adapter.getCount() + "-----currentFragment:" + adapter.getItem(1).getClass().getSimpleName());
    }

    /*菜单功能切换*/
    @Override
    public void switchMenu(String menuOption) {
        switch (menuOption) {
            case "dataCollection"://数据采集
                mViewpager.setCurrentItem(2);
                break;
            case "baiduMap"://在线地图
                mViewpager.setCurrentItem(1);
                switchMap(menuOption);
                break;
            case "localArcgisMap"://离线地图
                mViewpager.setCurrentItem(1);
                switchMap(menuOption);
                break;
            case "management"://管理
                mViewpager.setCurrentItem(3);
                break;

        }
    }

    /*获取BDLocation*/
    public Location getLocation() {
        if (mApp.getMyBinder() != null) {
            mLocation = mApp.getMyBinder() .getLocation();
        }
        return mLocation;
    }

    public LocationListener getLocationListener() {
        return mLocationListener;
    }
    /*
    * activity 生命周期
    * */

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "onStop: ---------------");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy: --------");
        TabFragment.onDestroy();
        mLocationManager.removeUpdates(mLocationListener);
        mApp.stopService();
    }

    /*返回键 */
    @Override
    public void onBackPressed() {
        if (DoubleClickExit.check()) {
            this.finish();
            System.exit(0);
        } else {
            showMessage("再按一次退出程序");
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            onBackPressed();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /* 消息提示*/
    private void showMessage(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();

    }

    /*跳转页面*/
    public static void start(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void showError(String msg) {
        mApp.showToastLongMessage(mContext,msg);
    }

    @Override
    public void UserRolResult(UserRolResultBean rolResultBean) {
        //Log.i(TAG, "UserRolResult: ---------------"+rolResultBean.toString());
        if (rolResultBean != null && rolResultBean.getCode().equals("200")) {
            SharedPreferenceUtil.setUserrealname(rolResultBean.getRealname());
            SharedPreferenceUtil.setUserworkunit(rolResultBean.getWorkunit());
            SharedPreferenceUtil.setGzdwdm(rolResultBean.getGZDWDM());
            SharedPreferenceUtil.setGzdwmc(rolResultBean.getGZDWMC());
        } else {
            mApp.showToastLongMessage(mContext,"权限获取失败");
            SharedPreferenceUtil.setUserrealname("");
            SharedPreferenceUtil.setUserworkunit("");
            SharedPreferenceUtil.setGzdwdm("");
            SharedPreferenceUtil.setGzdwmc("");
        }
    }

    /**
     * 数据初始化，加载代码表
     * @param codeBeans
     */
    @Override
    public void CodeTabResult(List<CodeBean> codeBeans) {
        CodeBeanDaoOpe.insertData(mContext,codeBeans);
        mCircleProgressDialog.dismiss();
    }

}
